package com.superhelper.receiver.web.controller;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.superhelper.common.domain.PushMsgType;
import com.superhelper.common.domain.mt.MtOrderPushEntity;
import com.superhelper.common.service.AliMQProducerService;
import com.superhelper.common.utils.HttpClientHelper;
import com.superhelper.common.utils.JsonHelper;
import com.superhelper.receiver.service.MtPushValidService;

/**
 * 美团消息推送
 */
@Controller
@RequestMapping("/push/mt")
public class MtReceiverController {
    protected Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private AliMQProducerService producer;

    @Autowired
    private MtPushValidService validService;

    @RequestMapping("/ping")
    @ResponseBody
    public String ping() {
        return "{\"data\":\"OK\"}";
    }

    @RequestMapping("/order/deliver_status")
    @ResponseBody
    public Map<String, String> deliverStatus(MtOrderPushEntity req, HttpServletRequest request,
            HttpServletResponse response) {
        return doService(req, PushMsgType.DELIVER_STATUS.getValue());
    }

    @RequestMapping("/order/poi_status")
    @ResponseBody
    public Map<String, String> poiStatus(MtOrderPushEntity req, HttpServletRequest request,
            HttpServletResponse response) {
        return doService(req, PushMsgType.POI_STATUS.getValue());
    }

    @RequestMapping("/order/create")
    @ResponseBody
    public Map<String, String> orderCreate(MtOrderPushEntity req, HttpServletRequest request,
            HttpServletResponse response) {
        return doService(req, PushMsgType.ORDER_CREATED.getValue());
    }

    @RequestMapping("/order/complete")
    @ResponseBody
    public Map<String, String> orderComplete(MtOrderPushEntity req, HttpServletRequest request,
            HttpServletResponse response) {
        return doService(req, PushMsgType.ORDER_COMPLETED.getValue());
    }

    @RequestMapping("/order/accept")
    @ResponseBody
    public Map<String, String> orderAccept(MtOrderPushEntity req, HttpServletRequest request,
            HttpServletResponse response) {
        return doService(req, PushMsgType.ORDER_ACCEPTED.getValue());
    }

    @RequestMapping("/order/cancel")
    @ResponseBody
    public Map<String, String> orderCancel(MtOrderPushEntity req, HttpServletRequest request,
            HttpServletResponse response) {
        return doService(req, PushMsgType.ORDER_APPLY_CANCEL.getValue());
    }

    @RequestMapping("/order/refund")
    @ResponseBody
    public Map<String, String> orderRefund(MtOrderPushEntity req, HttpServletRequest request,
            HttpServletResponse response) {
        return doService(req, PushMsgType.ORDER_REFUND.getValue());
    }

    private Map<String, String> doService(MtOrderPushEntity req, String pushType) {
        Map<String, String> result = new HashMap<>();
        result.put("data", "OK");
        // 空包检测，返回ok
        if (req == null || StringUtils.isBlank(req.getSign())) {
            return result;
        }
        log.info("{} params:{}", pushType, req);
        String orderStr = null;
        if (StringUtils.equalsIgnoreCase(pushType, PushMsgType.ORDER_APPLY_CANCEL.getValue())) {
            // StringUtils.equalsIgnoreCase(pushType,
            // PushMsgType.ORDER_APPLY_CANCEL.getValue())
            // StringUtils.equalsIgnoreCase(pushType,
            // PushMsgType.ORDER_AGREE_CANCEL.getValue())
            orderStr = req.getOrderCancel();
            @SuppressWarnings("unchecked")
            Map<String, Object> map = JsonHelper.fromJson(orderStr, Map.class);
            Integer reasonCode = NumberUtils.toInt(map.get("reasonCode") + "");
            if (reasonCode != null && 1103 == reasonCode) {
                pushType = PushMsgType.ORDER_APPLY_CANCEL.getValue();
            } else {
                pushType = PushMsgType.ORDER_CANCELED.getValue();
            }

        } else if (StringUtils.equalsIgnoreCase(pushType, PushMsgType.ORDER_REFUND.getValue())) {
            orderStr = req.getOrderRefund();
        } else if (StringUtils.equalsIgnoreCase(pushType, PushMsgType.DELIVER_STATUS.getValue())) {
            orderStr = req.getShippingStatus();
        } else if (StringUtils.equalsIgnoreCase(pushType, PushMsgType.POI_STATUS.getValue())) {
            orderStr = "{\"orderId\":" + System.currentTimeMillis() + "}";
        } else {
            orderStr = req.getOrder();
        }
        Long orderId = null;
        try {
            orderId = JsonHelper.getJsonNode(orderStr).get("orderId").asLong();
            if (!validService.valid(req)) {
                log.info("{} sign error orderId:{}", pushType, orderId);
                // result.put("data", "fail");
                // return result;
            }
            producer.sendMtOrder(orderId, pushType, req);
        } catch (Exception e) {
            log.error("{} deal error orderId:{}", pushType, orderId, e);
            result.put("data", "fail");
        }
        return result;
    }

    public static void main(String[] args) {
        String order = "{\"avgSendTime\":2400.0,\"caution\":\"\",\"cityId\":440100,\"ctime\":1494559202,\"daySeq\":\"3\",\"deliveryTime\":0,\"detail\":\"[{\\\"app_food_code\\\":\\\"黑胡椒鸡扒+卤蛋+时蔬  套餐\\\",\\\"box_num\\\":1,\\\"box_price\\\":1.8,\\\"food_discount\\\":1,\\\"food_name\\\":\\\"黑胡椒鸡扒+卤蛋+时蔬  套餐\\\",\\\"food_property\\\":\\\"\\\",\\\"price\\\":24,\\\"quantity\\\":1,\\\"sku_id\\\":\\\"\\\",\\\"spec\\\":\\\"\\\",\\\"unit\\\":\\\"份\\\"}]\",\"dinnersNumber\":0,\"ePoiId\":\"149741403821911\",\"extras\":\"[{\\\"mt_charge\\\":0,\\\"poi_charge\\\":13.02,\\\"reduce_fee\\\":13.02,\\\"remark\\\":\\\"购买黑胡椒鸡扒+卤蛋+时蔬  套餐原价24.0元现价10.98元\\\",\\\"type\\\":17},{}]\",\"hasInvoiced\":0,\"invoiceTitle\":\"\",\"isFavorites\":false,\"isPoiFirstOrder\":false,\"isThirdShipping\":0,\"latitude\":23.102147,\"logisticsCode\":\"0000\",\"longitude\":113.316357,\"orderId\":17006824010455777,\"orderIdView\":17006824010455777,\"originalPrice\":30.8,\"payType\":2,\"poiAddress\":\"广州市海珠区凤和江贝村陇西里59号之一4铺\",\"poiFirstOrder\":false,\"poiId\":1700682,\"poiName\":\"莫小厨住家饭（客村店）\",\"poiPhone\":\"18928956664\",\"poiReceiveDetail\":\"{\\\"actOrderChargeByMt\\\":[{\\\"comment\\\":\\\"活动款\\\",\\\"feeTypeDesc\\\":\\\"活动款\\\",\\\"feeTypeId\\\":10019,\\\"moneyCent\\\":0,\\\"setComment\\\":true,\\\"setFeeTypeDesc\\\":true,\\\"setFeeTypeId\\\":true,\\\"setMoneyCent\\\":true}],\\\"actOrderChargeByMtIterator\\\":{},\\\"actOrderChargeByMtSize\\\":1,\\\"actOrderChargeByPoi\\\":[{\\\"comment\\\":\\\"购买黑胡椒鸡扒+卤蛋+时蔬  套餐原价24.0元现价10.98元\\\",\\\"feeTypeDesc\\\":\\\"活动款\\\",\\\"feeTypeId\\\":10019,\\\"moneyCent\\\":1302,\\\"setComment\\\":true,\\\"setFeeTypeDesc\\\":true,\\\"setFeeTypeId\\\":true,\\\"setMoneyCent\\\":true}],\\\"actOrderChargeByPoiIterator\\\":{},\\\"actOrderChargeByPoiSize\\\":1,\\\"foodShareFeeChargeByPoi\\\":107,\\\"logisticsFee\\\":500,\\\"onlinePayment\\\":1778,\\\"setActOrderChargeByMt\\\":true,\\\"setActOrderChargeByPoi\\\":true,\\\"setFoodShareFeeChargeByPoi\\\":true,\\\"setLogisticsFee\\\":true,\\\"setOnlinePayment\\\":true,\\\"setWmPoiReceiveCent\\\":true,\\\"wmPoiReceiveCent\\\":1671}\",\"recipientAddress\":\"汇美商务中心 (北座二楼行者传媒)@#广东省广州市海珠区赤岗街道广州大道南83号\",\"recipientName\":\"陈(女士)\",\"recipientPhone\":\"13533138776\",\"shipperPhone\":\"\",\"shippingFee\":5.0,\"status\":2,\"total\":17.78,\"utime\":1494559208}";
        Long orderId = JsonHelper.getJsonNode(order).get("orderId").asLong();
        HttpClientHelper http = new HttpClientHelper();
        String url = "http://120.24.78.166:8080/superhelper-web-receiver/push/mt/order/create.do";
        Map<String, String> parameters = new HashMap<String, String>();
        parameters.put("developerId", "100727");
        parameters.put("ePoiId", "149741403821911");
        parameters.put("sign", "df71a725434f5faa8ee43a0c0abbc20207ae7c54");
        parameters.put("order", order);
        try {
            String aa = http.doPost(url, parameters);
            System.out.println(aa);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(orderId);

    }
}
